package com.sap.sap_mangers.service.Impl;


import com.alibaba.fastjson2.JSON;
import com.sap.sap_mangers.domain.LoginUser;
import com.sap.sap_mangers.pojo.TxCity.TxCityJson;
import com.sap.sap_mangers.pojo.User;
import com.sap.sap_mangers.pojo.Weather.Data;
import com.sap.sap_mangers.pojo.Weather.WeatherJson;
import com.sap.sap_mangers.service.CacheService;
import com.sap.sap_mangers.service.LoginService;
import com.sap.sap_mangers.until.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @author 阿东
 * @date 2022/7/1 [14:12]
 */
@Service
public class LoginServiceImpl implements LoginService {

    static List<String> ipList = new ArrayList<>();
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private CacheService cacheService;


    private static String randomIp() {
        ipList.add("14.135.209.191");
        StringBuilder huNanIp = new StringBuilder("43.250.201.");
        for (int i = 0; i < 255; i++) {
            huNanIp.append(i);
            ipList.add(huNanIp.toString());
            huNanIp = new StringBuilder("43.250.201.");
        }
        Random random = new Random();
        int indexIp = random.nextInt(255);
        return ipList.get(indexIp);
    }

    @Override
    public SimpleJson login(User user) {
        //AuthenticationManager authenticate进行用户认证
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(usernamePasswordAuthenticationToken);
        //如果认证没通过，给出对应的提示
        if (Objects.isNull(authenticate)) {
            throw new RuntimeException("登录失败");
        }
        //如果认证通过了，使用userid生成jwt
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String userName = loginUser.getUser().getUsername();
        String jwt = JwtUtil.createJWT(userName);
        Map<String, String> map = new HashMap<>(31);
        map.put("token", jwt);
        //把完整的用户信息存入redis username作为key
        String userJson = JSON.toJSONString(loginUser);
        cacheService.loginCacheUserToRedis(userName, userJson);
        return new SimpleJson(0, "登录成功", map);
    }



    @Override
    public SimpleJson quitLogin() {
        //获取SecurityContextHolder中的用户id
        String username = JwtUtil.getUserForToken();
        //删除redis中的值
        redisTemplate.delete("login:" + username);
        return new SimpleJson(0, "退出登录成功");
    }

    @Override
    public Data getIpAndWeather(HttpServletRequest request) {
        String city = getCityFun(request);
        String urls = "http://wthrcdn.etouch.cn/weather_mini?city=" + city;
        String weatherInfo = WeatherUtil.getWeatherInfo(urls);
        WeatherJson weatherJson = JSON.parseObject(weatherInfo, WeatherJson.class);
        assert weatherJson != null;
        return weatherJson.getData();
    }

    @Override
    public SimpleJson getCity(HttpServletRequest request) {
        return new SimpleJson(getCityFun(request));
    }

    private String getCityFun(HttpServletRequest request) {
        String ipAddress = IpUtil.getIpAddr(request);
        if (Objects.equals(ipAddress, "127.0.0.1")) {
            ipAddress = randomIp();
        }
        String url = "https://apis.map.qq.com/ws/location/v1/ip?ip=" + ipAddress + "&key=W6HBZ-AUKLJ-ALDFP-KGML7-TTQTJ-VUF42";
        String resultString = restTemplate.getForObject(url, String.class);
        TxCityJson cityJsonResult = com.alibaba.fastjson.JSON.parseObject(resultString, TxCityJson.class);
        String city = "";
        assert cityJsonResult != null;
        if (cityJsonResult.getResult().getAd_info().getDistrict().length() != 0) {
            city = cityJsonResult.getResult().getAd_info().getDistrict();
        } else if (cityJsonResult.getResult().getAd_info().getCity().length() != 0) {
            city = cityJsonResult.getResult().getAd_info().getCity();
        } else if (cityJsonResult.getResult().getAd_info().getProvince().length() != 0) {
            city = cityJsonResult.getResult().getAd_info().getProvince();
        } else if (cityJsonResult.getResult().getAd_info().getNation().length() != 0) {
            city = cityJsonResult.getResult().getAd_info().getNation();
        }
        return city;
    }


}
